import React, { PropsWithChildren, useMemo } from "react";
import { connect, useDispatch } from "react-redux";
import { CustomCombinedState } from "../../store/reducers";
import { ProfileState } from "../../store/reducers/profile";
import { RouteComponentProps } from "react-router";
import NavHeader from "../../components/Nav";
import { Button, Alert, Avatar, Upload, message } from "bigbear-ui";
import useAuth from "@/components/hooks/useAuth";
import actions from "@/store/actions/profile";

type Props = PropsWithChildren<ProfileState & RouteComponentProps>;

function Profile(props: Props) {
	useAuth(props.location.pathname);
	const disptach = useDispatch();
	const content = useMemo(() => {
		let content;
		if (props.loginState === "LOGIN") {
			content = (
				<div className="profile-info">
					<div className="bigbear-layout-block-default">
						{props.user.avatar ? (
							<Avatar size="lg">
								<img src={props.user.avatar} alt=""></img>
							</Avatar>
						) : (
							<Upload
								filename={() => "avatar"}
								type="img"
								uploadNumber={1}
								successCallback={(e) => {
									message.success("上传成功", {});
									disptach(actions.changeAvatar(e.data));
								}}
								failCallback={(e) => message.danger(e, {})}
							></Upload>
						)}
						<Alert title="用户名" description={props.user.username}></Alert>
						<Alert title="邮箱" description={props.user.email}></Alert>
					</div>
					<Button btnType="primary" onClick={() => disptach(actions.logout())}>
						退出登录
					</Button>
				</div>
			);
		} else {
			content = (
				<div className="profile-unlogin">
					<Alert
						type="warning"
						title="当前未登录"
						description="亲爱的用户你好，你当前尚未登录，请你选择注册或者登录"
					/>
					<div className="profile-btn" style={{ textAlign: "center", padding: "50px" }}>
						<Button onClick={() => props.history.push("/login")}>登录</Button>
						<Button
							style={{ marginLeft: "50px" }}
							onClick={() => props.history.push("/register")}
						>
							注册
						</Button>
					</div>
				</div>
			);
		}
		return content;
	}, [props.history, props.loginState, disptach, props.user]);

	return (
		<section>
			<NavHeader history={props.history}>个人中心</NavHeader>
			{content}
		</section>
	);
}

let mapStateToProps = (state: CustomCombinedState): ProfileState => state.profile;

export default connect(mapStateToProps)(Profile);
